package org.ktx.osr.audio

import android.util.Log
import java.io.File
import java.io.FileOutputStream
import java.io.RandomAccessFile
import java.nio.ByteBuffer
import java.nio.ByteOrder

/**
 * WAV文件处理器
 * 负责WAV文件的创建、写入和头部更新
 */
class WavFileHandler(
    private val outputFile: File,
    private val sampleRate: Int = 44100,
    private val channelCount: Int = 2,
    private val bitsPerSample: Int = 16
) {
    private var fileOutputStream: FileOutputStream? = null
    private var totalAudioLen = 0
    private var isInitialized = false

    companion object {
        private const val TAG = "WavFileHandler"
    }

    /**
     * 初始化WAV文件
     */
    fun initialize(): Boolean {
        if (isInitialized) return true
        
        return try {
            fileOutputStream = FileOutputStream(outputFile)
            writeWavHeader()
            isInitialized = true
            Log.d(TAG, "WAV file initialized successfully")
            true
        } catch (e: Exception) {
            Log.e(TAG, "Failed to initialize WAV file", e)
            release()
            false
        }
    }

    /**
     * 写入音频数据
     */
    fun writeAudioData(data: ByteArray, size: Int) {
        if (!isInitialized) return
        
        try {
            fileOutputStream?.write(data, 0, size)
            totalAudioLen += size
        } catch (e: Exception) {
            Log.e(TAG, "Error writing audio data", e)
        }
    }

    /**
     * 完成写入并更新文件头
     */
    fun finishWriting() {
        if (!isInitialized) return
        
        try {
            fileOutputStream?.flush()
            updateWavHeader()
            Log.d(TAG, "WAV file writing completed")
        } catch (e: Exception) {
            Log.e(TAG, "Error finishing WAV file writing", e)
        }
    }

    /**
     * 写入WAV文件头
     */
    private fun writeWavHeader() {
        val header = ByteArray(44)
        val buffer = ByteBuffer.wrap(header)
        buffer.order(ByteOrder.LITTLE_ENDIAN)

        // RIFF header
        buffer.put("RIFF".toByteArray())
        buffer.putInt(0) // File size (will be updated later)
        buffer.put("WAVE".toByteArray())

        // Format chunk
        buffer.put("fmt ".toByteArray())
        buffer.putInt(16) // Format chunk size
        buffer.putShort(1.toShort()) // Audio format (PCM)
        buffer.putShort(channelCount.toShort()) // Number of channels
        buffer.putInt(sampleRate) // Sample rate
        buffer.putInt(sampleRate * channelCount * bitsPerSample / 8) // Byte rate
        buffer.putShort((channelCount * bitsPerSample / 8).toShort()) // Block align
        buffer.putShort(bitsPerSample.toShort()) // Bits per sample

        // Data chunk
        buffer.put("data".toByteArray())
        buffer.putInt(0) // Data size (will be updated later)

        fileOutputStream?.write(header)
    }

    /**
     * 更新WAV文件头
     */
    private fun updateWavHeader() {
        try {
            val raf = RandomAccessFile(outputFile, "rw")

            // Update file size
            raf.seek(4)
            raf.writeInt(36 + totalAudioLen)

            // Update data size
            raf.seek(40)
            raf.writeInt(totalAudioLen)

            raf.close()
        } catch (e: Exception) {
            Log.e(TAG, "Error updating WAV header", e)
        }
    }

    /**
     * 释放资源
     */
    fun release() {
        try {
            fileOutputStream?.close()
        } catch (e: Exception) {
            Log.e(TAG, "Error releasing WAV file resources", e)
        } finally {
            fileOutputStream = null
            totalAudioLen = 0
            isInitialized = false
        }
    }
}
